package com.freewater.springboot.demo.conversion.databinder;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        applicationContext.registerShutdownHook();
        final Validator validator = applicationContext.getBean(Validator.class);
        //
        PersonForm personForm = new PersonForm();
        DataBinder binder = new DataBinder(personForm);
        binder.addValidators(validator);
        //
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues.addPropertyValue(new PropertyValue("name", "张三"));
        propertyValues.addPropertyValue(new PropertyValue("age", -1));
        binder.bind(propertyValues);
        //
        binder.validate();
        final BindingResult bindingResult = binder.getBindingResult();
        for (ObjectError error : bindingResult.getAllErrors()) {
            System.out.println(error.getObjectName() + "\t" + error.getDefaultMessage());
        }
    }
}
